package com.lovo.frame;

import com.lovo.pojo.UsersDO;
import com.lovo.service.UserService;
import com.lovo.service.impl.UserServiceImpl;
import com.lovo.util.DBUtil;
import com.lovo.util.Util;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Login extends JPanel implements ActionListener {
    private Icon loginImg = Util.getIcon("/image/buttonLand.jpg");
    private ATM frame;
    private JButton loginBtn;
    private JTextField textField1;
    private JPasswordField passwordField;
    private int count = 3;
    private UserService userService = new UserServiceImpl();

    public Login(ATM frame) {
        this.frame = frame;
        this.setLayout(null);

        JLabel textlabel1 = new JLabel("用户名：");
        textlabel1.setBounds(200, 150, 50, 30);
        this.add(textlabel1);
        //单行输入框
        textField1 = new JTextField();
        textField1.setBounds(250, 150, 250, 30);
        this.add(textField1);

        JLabel textlabel2 = new JLabel("密码：");
        textlabel2.setBounds(200, 200, 50, 30);
        this.add(textlabel2);
        //单行密码输入框
        passwordField = new JPasswordField();
        passwordField.setBounds(250, 200, 250, 30);
        this.add(passwordField);

        this.setOpaque(false);
        loginBtn = new JButton(loginImg);
        loginBtn.setBounds(200, 320, 100, 20);
        this.add(loginBtn);
        loginBtn.addActionListener(this);

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == loginBtn) {
            String username = textField1.getText();
            String pwd = passwordField.getText();
//            for (int i = 0; i <frame.getUsers().size(); i++) {
//                if (frame.getUsers().get(i).getUserName().equals(textField1.getText()) && frame.getUsers().get(i).getPassWord().equals(passwordField.getText())) {
//                    frame.setNum(i);
//                    JOptionPane.showMessageDialog(this, "登录成功");
//                    count = 3;
//                    frame.switchPanel("菜单");
//                    return;
//                }

            UsersDO users = userService.getByUsernameAndPwd(username, pwd);
            if (users != null) {
                frame.setLoginUser(users);
                frame.switchPanel("菜单");
                return;
            }
            --count;
            if (count == 0) {
                JOptionPane.showMessageDialog(this, "账号已冻结，请联系028-88866612");
                System.exit(0);
            } else {
                JOptionPane.showMessageDialog(this, "密码错误，请重新输入" + "您还有" + count + "次机会");
            }
        }
    }
}
